import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../core/providers/app_providers.dart';
import '../../core/types/app_types.dart';

/**
 * 笔记编辑器组件
 * 支持 Markdown 编辑和实时保存
 */
class NoteEditor extends ConsumerStatefulWidget {
  const NoteEditor({super.key});

  @override
  ConsumerState<NoteEditor> createState() => _NoteEditorState();
}

class _NoteEditorState extends ConsumerState<NoteEditor> {
  final TextEditingController _titleController = TextEditingController();
  final TextEditingController _contentController = TextEditingController();
  final FocusNode _titleFocusNode = FocusNode();
  final FocusNode _contentFocusNode = FocusNode();
  
  Note? _currentNote;
  bool _isModified = false;
  bool _isSaving = false;

  @override
  void initState() {
    super.initState();
    
    // 监听文本变化
    _titleController.addListener(_onTextChanged);
    _contentController.addListener(_onTextChanged);
  }

  @override
  void dispose() {
    _titleController.dispose();
    _contentController.dispose();
    _titleFocusNode.dispose();
    _contentFocusNode.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final currentNote = ref.watch(currentNoteProvider);
    
    // 当选中的笔记发生变化时，更新编辑器内容
    if (currentNote != _currentNote) {
      _loadNote(currentNote);
    }

    return Container(
      decoration: BoxDecoration(
        color: Theme.of(context).scaffoldBackgroundColor,
      ),
      child: currentNote == null
          ? _buildEmptyState()
          : _buildEditor(),
    );
  }

  /**
   * 构建空状态界面
   */
  Widget _buildEmptyState() {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Icon(
            Icons.note_outlined,
            size: 80,
            color: Theme.of(context).disabledColor,
          ),
          const SizedBox(height: 16),
          Text(
            '选择一篇笔记开始编辑',
            style: TextStyle(
              fontSize: 18,
              color: Theme.of(context).disabledColor,
            ),
          ),
          const SizedBox(height: 8),
          Text(
            '或者创建一篇新笔记',
            style: TextStyle(
              fontSize: 14,
              color: Theme.of(context).disabledColor,
            ),
          ),
        ],
      ),
    );
  }

  /**
   * 构建编辑器界面
   */
  Widget _buildEditor() {
    return Column(
      children: [
        // 工具栏
        _buildToolbar(),
        
        // 分割线
        Divider(
          height: 1,
          color: Theme.of(context).dividerColor,
        ),
        
        // 编辑区域
        Expanded(
          child: Padding(
            padding: const EdgeInsets.all(16),
            child: Column(
              children: [
                // 标题输入框
                TextField(
                  controller: _titleController,
                  focusNode: _titleFocusNode,
                  decoration: const InputDecoration(
                    hintText: '请输入标题...',
                    border: InputBorder.none,
                  ),
                  style: const TextStyle(
                    fontSize: 24,
                    fontWeight: FontWeight.bold,
                  ),
                  maxLines: 1,
                ),
                
                const SizedBox(height: 16),
                
                // 内容输入框
                Expanded(
                  child: TextField(
                    controller: _contentController,
                    focusNode: _contentFocusNode,
                    decoration: const InputDecoration(
                      hintText: '开始写作...',
                      border: InputBorder.none,
                    ),
                    style: const TextStyle(
                      fontSize: 16,
                      height: 1.6,
                    ),
                    maxLines: null,
                    expands: true,
                    textAlignVertical: TextAlignVertical.top,
                  ),
                ),
              ],
            ),
          ),
        ),
      ],
    );
  }

  /**
   * 构建工具栏
   */
  Widget _buildToolbar() {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
      decoration: BoxDecoration(
        color: Theme.of(context).scaffoldBackgroundColor,
        border: Border(
          bottom: BorderSide(
            color: Theme.of(context).dividerColor,
          ),
        ),
      ),
      child: Row(
        children: [
          // 笔记信息
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  _currentNote?.title.isEmpty == true ? '无标题' : _currentNote?.title ?? '',
                  style: const TextStyle(
                    fontSize: 14,
                    fontWeight: FontWeight.w600,
                  ),
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                ),
                const SizedBox(height: 2),
                Row(
                  children: [
                    Text(
                      '最后修改: ${_formatDate(_currentNote?.updatedAt ?? DateTime.now())}',
                      style: TextStyle(
                        fontSize: 12,
                        color: Theme.of(context).textTheme.bodySmall?.color,
                      ),
                    ),
                    if (_isModified) ...[
                      const SizedBox(width: 8),
                      Container(
                        padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2),
                        decoration: BoxDecoration(
                          color: Colors.orange.withOpacity(0.1),
                          borderRadius: BorderRadius.circular(4),
                        ),
                        child: const Text(
                          '未保存',
                          style: TextStyle(
                            fontSize: 10,
                            color: Colors.orange,
                          ),
                        ),
                      ),
                    ],
                    if (_isSaving) ...[
                      const SizedBox(width: 8),
                      const SizedBox(
                        width: 12,
                        height: 12,
                        child: CircularProgressIndicator(strokeWidth: 2),
                      ),
                    ],
                  ],
                ),
              ],
            ),
          ),
          
          // 工具按钮
          Row(
            children: [
              IconButton(
                onPressed: _isModified ? _saveNote : null,
                icon: const Icon(Icons.save),
                tooltip: '保存',
              ),
              IconButton(
                onPressed: () {
                  _showDeleteDialog();
                },
                icon: const Icon(Icons.delete_outline),
                tooltip: '删除',
              ),
              IconButton(
                onPressed: () {
                  // TODO: 实现分享功能
                },
                icon: const Icon(Icons.share_outlined),
                tooltip: '分享',
              ),
            ],
          ),
        ],
      ),
    );
  }

  /**
   * 加载笔记内容
   */
  void _loadNote(Note? note) {
    _currentNote = note;
    
    if (note != null) {
      _titleController.text = note.title;
      _contentController.text = note.content;
    } else {
      _titleController.clear();
      _contentController.clear();
    }
    
    _isModified = false;
  }

  /**
   * 文本变化处理
   */
  void _onTextChanged() {
    if (_currentNote != null) {
      final hasChanges = _titleController.text != _currentNote!.title ||
          _contentController.text != _currentNote!.content;
      
      if (hasChanges != _isModified) {
        setState(() {
          _isModified = hasChanges;
        });
        
        // 自动保存（延迟2秒）
        if (hasChanges) {
          Future.delayed(const Duration(seconds: 2), () {
            if (_isModified && mounted) {
              _saveNote();
            }
          });
        }
      }
    }
  }

  /**
   * 保存笔记
   */
  Future<void> _saveNote() async {
    if (_currentNote == null || !_isModified || _isSaving) return;
    
    setState(() {
      _isSaving = true;
    });
    
    try {
      final updatedNote = _currentNote!.copyWith(
        title: _titleController.text.trim(),
        content: _contentController.text,
        updatedAt: DateTime.now(),
        syncStatus: SyncStatus.pending,
      );
      
      await ref.read(appDataNotifierProvider.notifier).updateNote(updatedNote);
      
      // 更新当前笔记引用
      ref.read(currentNoteProvider.notifier).setNote(updatedNote);
      
      setState(() {
        _isModified = false;
        _isSaving = false;
      });
    } catch (e) {
      setState(() {
        _isSaving = false;
      });
      
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('保存失败: $e')),
        );
      }
    }
  }

  /**
   * 显示删除确认对话框
   */
  void _showDeleteDialog() {
    if (_currentNote == null) return;
    
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('删除笔记'),
        content: Text('确定要删除笔记"${_currentNote!.title}"吗？此操作不可撤销。'),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(context).pop(),
            child: const Text('取消'),
          ),
          TextButton(
            onPressed: () async {
              try {
                await ref.read(appDataNotifierProvider.notifier).deleteNote(_currentNote!.id);
                
                // 清除当前选中的笔记
                ref.read(currentNoteProvider.notifier).clearNote();
                
                if (context.mounted) {
                  Navigator.of(context).pop();
                }
              } catch (e) {
                if (context.mounted) {
                  ScaffoldMessenger.of(context).showSnackBar(
                    SnackBar(content: Text('删除笔记失败: $e')),
                  );
                }
              }
            },
            child: const Text('删除'),
          ),
        ],
      ),
    );
  }

  /**
   * 格式化日期
   */
  String _formatDate(DateTime date) {
    final now = DateTime.now();
    final difference = now.difference(date);

    if (difference.inDays == 0) {
      return '今天 ${date.hour.toString().padLeft(2, '0')}:${date.minute.toString().padLeft(2, '0')}';
    } else if (difference.inDays == 1) {
      return '昨天 ${date.hour.toString().padLeft(2, '0')}:${date.minute.toString().padLeft(2, '0')}';
    } else if (difference.inDays < 7) {
      return '${difference.inDays}天前';
    } else {
      return '${date.year}/${date.month}/${date.day}';
    }
  }
}